/**
 * Created by tdzl2003 on 8/24/16.
 */
import React from 'react';
import { Popconfirm, Button,Checkbox ,Select} from 'antd';
import {get, $delete, put} from '../../logics/rpc';
import ObjectTable from '../../components/ObjectTable';
import AddRoleModal from './AddRoleModal';

import AntdCheckbox from '../../components/AntdCheckbox';

const CheckboxGroup = Checkbox.Group;

const plainOptions = [
    {label: '查看管理员列表和查看角色列表', value: 'account.list' },
    {label: '创建管理员，更改管理员角色，重置其它管理员密码等', value: 'account.manage' },
    {label: '编辑角色列表，编辑角色权限等', value: 'account.role' },
    {label: '查看用户列表', value: 'user.list' },
    {label: '编辑用户信息', value: 'user.edit' },
    {label: '查看提现记录', value: 'drawout.list' },
    {label: '给提现添加备注', value: 'drawout.remark' },
    {label: '编辑角色列表，编辑角色权限等', value: 'drawout.process' },
    {label: '查看商品列表', value: 'good.list' },
    {label: '修改商品基本信息', value: 'good.edit' },
    {label: '修改商品提成', value: 'good.editExtract' },
    {label: '创建新商品', value: 'good.create' },
    {label: '下架商品', value: 'good.delete' },
];
const options = [
    'account.role',
    'drawout.list',
    'good.edit'
];

export default class RoleList extends React.Component{
    state={
        setRoleModalVisible: false,
        addRoleModalVisible: false,
        privList:[],
    };

    async componentWillMount() {
        const fetchPrivsData = (params) => get('get /admin/role/list?page=0&pageSize=1', params);
        try{
            const {data, totalCount} = await fetchPrivsData({});
        }catch (err) {
            if (__DEV__){
                console.log("获取角色失败",err);
            }
        }
    }
    fetchData = (params) => {
        const ret = get('/admin/role/list', params);
        ret.then(function(res) {
            const dataArr = res.data;
            for(let i =0;i<dataArr.length;i++){
              if(dataArr[i].hasOwnProperty("role")){
                  //假的角色的数据
                  if (!dataArr[i].role) {
                      dataArr[i].role = {id: 0, name: ""};
                  }
              }else{
                  let privsArr = [];
                  let privsDataArr = dataArr[i].privs;
                  for(let j= 0;j<privsDataArr.length;j++){
                      privsArr.push(privsDataArr[j]);
                  }
                  dataArr[i].defaultPrivs = privsArr;
                  let tempUserName = "";
                  let tempUserArr = dataArr[i]["users"];
                  if(tempUserArr.length > 0){
                      for(let k = 0; k<tempUserArr.length;k++){
                          tempUserName += tempUserArr[k].account;
                          if(k!= tempUserArr.length-1){
                              tempUserName += ",";
                          }
                      }
                  }else{
                      tempUserName = "";
                  }
                  dataArr[i].userName = tempUserName;
              }
            }
        });
        return ret;
    };
    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            width: 60,
        }, {
            title: '用户列表',
            dataIndex: 'userName',
            width: 60,
        },  {
            title: '角色名',
            dataIndex: 'name',
            width: 120,

        },{
            title: '操作',
            width: 60,
            render: acc => (
                <div>
                    <Popconfirm placement="topRight" title={`确认删除角色:${acc.name}吗？`} onConfirm={()=>this.deleteRole(acc)}>
                        <Button size="small">删除角色</Button>
                    </Popconfirm>
                </div>
            ),

        }];

    async deleteRole(acc) {
        try {
            await $delete(`/admin/role/${acc.id}`);
            this.refs.table.removeItem(acc);
        } catch (err) {
            if (__DEV__){
                console.log("删除角色失败",err);
            }
            alert("删除角色失败");
        }
    };



    dismissAddRole = () => {
        this.setState({
            addRoleModalVisible:false
        });
    };

    //添加角色
    renderHeader = () => {
        return (
            <div>
                <Button onClick={this.showAddRole}>添加角色</Button>
            </div>
        );
    };
    //显示添加角色
    showAddRole = () =>{
        this.setState({
            addRoleModalVisible: true
        });
    };

    onRoleAdded = () => {
        this.refs.table.refresh();
    };

    //设置权限的方法
    setPrivs = async(acc,checkedValues) =>{

        let   checkName =  encodeURIComponent(checkedValues.value);
        try {
            await put(`/admin/role/${acc.id}/${checkName}`,{
                value:checkedValues.status,
            });
            console.log("保存成功");
        }catch (err){
            console.log("设置权限失败",err);
        }


    };
    render() {




        const { addRoleModalVisible} = this.state;
        return (
            <div>
                <ObjectTable
                    ref="table"
                    expandedRowRender={(acc,record) =>
                        <AntdCheckbox
                            dataSource={plainOptions}
                            defaultValue={acc.defaultPrivs}//这里设置的是quan
                            onChange={( checkedValues) => this.setPrivs(acc,checkedValues)}
                            />
                    }
                    columns={this.columns}
                    fetchData={this.fetchData}
                    title={this.renderHeader} //添加角色

                />

                <AddRoleModal
                    visible={addRoleModalVisible}
                    dismiss={this.dismissAddRole}
                    onAdded={this.onRoleAdded}
                />
            </div>
        );
    }
}
